const path = require('path');
const webpack = require('webpack');
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const { defineConfig } = require('@vue/cli-service');
//const TerserPlugin = require('terser-webpack-plugin');
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
const BundleAnalyzerPlugin =
  require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

const productionGzipExtensions = [
  'js',
  'css',
  'json',
  'txt',
  'html',
  'ico',
  'svg',
];
const isProd = process.env.NODE_ENV === 'production';
const glob = require('glob');
const pagesInfo = require('./project.config');
const pages = {};
//const cdnServer = '//lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M';
const cdnServer = '//realenet-1301408934.file.myqcloud.com/macc/lib';

//CDN信息
const assetsCDN = {
  // webpack build externals
  externals: [
    {
      // moment: 'moment',
      // vue: 'Vue',
      // 'vue-router': 'VueRouter',
      // vuex: 'Vuex',
      // 'ant-design-vue': 'antd',
      // axios: 'axios',
      // clipboard: 'ClipboardJS',
      // 'js-cookie': 'Cookies',
      // echarts: 'echarts',
      // d3: 'd3',
      // xlsx: 'XLSX',
    },
  ],

  css: [],
  js: [
    // cdnServer + '/moment-2.29.1/min/moment-with-locales.min.js',
    // cdnServer + '/vue.min.js',
    // cdnServer + '/vue-router.min.js',
    // cdnServer + '/vuex.js',
    // cdnServer + '/antd.min.js',
    // cdnServer + '/axios.min.js',
    // cdnServer + '/clipboard.min.js',
    // cdnServer + '/js.cookie.min.js',
    // cdnServer + '/echarts.min.js',
    // cdnServer + '/d3.min.js',
    // cdnServer + '/xlsx.full.min.js',
  ],
};

//组装多入口页面配置
glob.sync('./src/project/**/main.js').forEach((entry) => {
  let chunk = entry.match(/\.\/src\/project\/(.*)\/main\.js/)[1];
  const curr = pagesInfo[chunk];

  // 海外的情况只放开adminIntl项目
  if (process.env.VUE_APP_MACC_ENV == 'INTL') {
    if (process.env.VUE_APP_MACC_BUSINESS_ENV == 'authSys') {
      if (chunk !== 'authSys') {
        return;
      }
    } else if (chunk !== 'adminIntl') {
      return;
    }
  }

  if (curr) {
    pages[chunk] = {
      entry,
      ...curr,
      chunk: ['chunk-vendors', 'chunk-common', chunk],
    };
  }
});

module.exports = defineConfig({
  // runtimeCompiler: true, //使用编译器
  //资源访问基础路径
  publicPath: process.env.VUE_APP_MACC_PUBLICPATH || '',
  productionSourceMap: false,
  devServer: {
    historyApiFallback: true,
    allowedHosts: 'all',
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
    port: 8080,
    proxy: {
      '/webproxy': {
        //此处要与 /services/api.js 中的 API_PROXY_PREFIX 值保持一致
        // target: process.env.VUE_APP_API_BASE_URL,
        target: `${process.env.VUE_APP_MACC_SERVER}`,
        // target:'http://172.30.82.53/',
        changeOrigin: true,
        // publicPath:"/adminx/"
        // pathRewrite: {
        //   '^/webproxy': '',
        // },
      },
    },
  },

  pluginOptions: {
    'style-resources-loader': {
      //引入less 全局变量
      preProcessor: 'less',
      patterns: [path.resolve(__dirname, './src/assets/skin/color.less')],
    },
  },
  configureWebpack: (config) => {
    config.plugins.push(new NodePolyfillPlugin());
    // Ignore all locale files of moment.js
    //config.plugins.push(new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/));

    // config.module
    //   .rule('eslink')
    //   .use('eslint-loader')
    //   .loader('eslint-loader')
    //   .options({ fix: true });

    config.plugins.push(
      new webpack.container.ModuleFederationPlugin({
        name: 'layout', //模块名
        filename: 'remoteEntry.js',
        remotes: {
          firewallLicense:
            'firewallLicense@' +
            process.env.VUE_APP_FIREWALL_EX_URL +
            'remoteEntry.js',
        },
        shared: {
          vue: { singleton: true, eager: true },
          vuex: { singleton: true, eager: true },
        },
      })
    );

    //intro 引导
    config.plugins.push(
      new webpack.ProvidePlugin({
        introJs: ['intro.js'],
      })
    );

    // 生产环境下配置
    if (isProd) {
      //删除console.log和debugger
      // config.plugins.push(
      //   new TerserPlugin({
      //     cache: true,
      //     sourceMap: false,
      //     // 多进程
      //     parallel: true,
      //     terserOptions: {
      //       ecma: undefined,
      //       warnings: false,
      //       parse: {},
      //       compress: {
      //         drop_console: true,
      //         drop_debugger: true,
      //         pure_funcs: ['console.log'], // 移除console
      //       },
      //     },
      //   })
      // );
      // 生产环境下将资源压缩成gzip格式
      config.plugins.push(
        new CompressionWebpackPlugin({
          algorithm: 'gzip',
          test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
          threshold: 10240,
          minRatio: 0.8,
        })
      );

      //lodash 库按需打包
      config.plugins.push(
        new LodashModuleReplacementPlugin({ shorthands: true })
      );

      //生产环境不打包cdn库
      config.externals = assetsCDN.externals;
      //config.devtool = 'source-map';
      //config.devtool = 'eval-cheap-module-source-map';
    } else {
      config.devtool = 'source-map';
      //config.devtool = 'eval-cheap-module-source-map';
    }
  },
  chainWebpack: (config) => {
    // 移除 prefetch，preload 资源预加载插件
    config.plugins.delete('prefetch-adminx');
    config.plugins.delete('prefetch-adminIntl');
    //修复热更新
    config.resolve.symlinks(true);
    // config.externals({ './cptable': 'var cptable' });
    //配置路径别名
    config.resolve.alias
      .set('@', path.join(__dirname, 'src'))
      .set('@views', path.join(__dirname, 'src/views'))
      .set('@utils', path.join(__dirname, 'src/utils'))
      .set('@router', path.join(__dirname, 'src/router'))
      .set('@cache', path.join(__dirname, 'src/cache'))
      .set('@mixin', path.join(__dirname, 'src/mixin'))
      .set('@directives', path.join(__dirname, 'src/directives'))
      .set('@projectCommon', path.join(__dirname, 'src/projectCommon'))
      .set('@project', path.join(__dirname, 'src/project'))
      .set('@assets', path.join(__dirname, 'src/assets'))
      .set('@components', path.join(__dirname, 'src/components'));

    (config) => config.plugins.delete('named-chunks');

    // 生产环境下使用CDN
    if (isProd) {
      // config.plugin('html')
      //   .tap(args => {
      //     args[0].cdn = assetsCDN
      //     args[0].chunksSortMode = "none";
      //   return args
      // })
      // 压缩图片
      // config.module
      //   .rule('images')
      //   .test(/\.(png|jpe?g|gif|svg)(\?.*)?$/)
      //   .use('image-webpack-loader')
      //   .loader('image-webpack-loader')
      //   .options({
      //     mozjpeg: { progressive: true, quality: 65 },
      //     optipng: { enabled: false },
      //     pngquant: { quality: [0.65, 0.9], speed: 4 },
      //     gifsicle: { interlaced: false },
      //   });

      // 多页面cdn添加
      Object.keys(pagesInfo).forEach((page) => {
        config.plugin(`html-${page}`).tap((args) => {
          // html中添加cdn
          args[0].cdn = assetsCDN;
          // 修复 Lazy loading routes Error
          args[0].chunksSortMode = 'none';
          return args;
        });
      });

      const terser = config.optimization.minimizer('terser');
      terser.tap((args) => {
        const { terserOptions } = args[0];
        Object.assign(terserOptions, {
          compress: {
            ...terserOptions.compress,
            drop_console: true,
            drop_debugger: true,
          },
          format: {
            comments: /@license/i,
          },
        });
        return args;
      });

      // config.optimization.minimizer('terser').tap((args) => {
      //   console.log('=====1', JSON.stringify(args), args[0]);
      //   //args[0].parallel = 4;
      //   Object.assign(args[0].terserOptions.compress, {
      //     drop_console: true,
      //     drop_debugger: true,
      //     pure_funcs: ['console.log'],
      //   });
      //   // args[0].terserOptions.compress.warnings = true;
      //   // args[0].terserOptions.compress.drop_console = true;
      //   // args[0].terserOptions.compress.drop_debugger = true;
      //   // args[0].terserOptions.compress.pure_funcs = ['console.log']; // 移除console
      //   console.log('=====2', JSON.stringify(args), args[0]);
      //   return args;
      // });

      // 打包分析
      config.plugin('webpack-report').use(BundleAnalyzerPlugin, [
        {
          analyzerMode: 'static',
        },
      ]);
    }
  },
  pages,
  css: {
    // extract: isProd,
    // sourceMap: false,
    loaderOptions: {
      less: {
        // hack: ` @import "${path.join(
        //   __dirname,
        //   './src/assets/skin/atndvariables.less'
        // )}";
        // `,
        lessOptions: {
          modifyVars: {
            'primary-color': '#2b6afd',
            'link-color': '#2b6afd',
            'border-radius-base': '4px',
          },
          javascriptEnabled: true,
        },
      },
    },
  },
});
